<template>
  <t-drawer
    :title="title"
    placement="right"
    :width="640"
    :visible="visible"
    :destroyOnClose="true"
    @close="
      () => {
        $emit('cancel');
      }
    "
  >
    <a-spin :spinning="loading" :tip="loadingText">
      <tool-bar>
        <template slot="toolBtn" slot-scope="scope">
          <template v-if="type != 'user'">
            <a-button
              class="cu-btn-primary"
              icon="plus"
              @click="handleAccess('all')"
              >{{ $ct("batchLicensing", "批量授权") }}</a-button
            >
            <a-button
              :disabled="roleUuid == '402888e5575f3ab7015760002082076e'"
              :class="
                roleUuid !== '402888e5575f3ab7015760002082076e'
                  ? 'cu-btn-danger'
                  : ''
              "
              type="link"
              @click="handleAccess('all', 'cancellation')"
              >{{ $ct("batchCancel", "批量取消") }}</a-button
            >
          </template>
          <template v-else>
            <a-button class="cu-btn-primary" icon="plus" @click="addUser">
              添加用户
            </a-button>
          </template>
        </template>
      </tool-bar>
      <div class="table-content">
        <a-table
          v-if="loadSuccess"
          size="small"
          :columns="columns"
          :data-source="menuTreeData"
          rowKey="id"
          :rowSelection="type == 'user' ? null : rowSelection"
          :pagination="type != 'user' ? false : pagination"
          defaultExpandAllRows
          :scroll="scrollXY"
          @change="pageChange"
        >
          <span slot="renderUserHeadPortrait" slot-scope="text">
            <img :src="text" alt="" class="business-license" />
          </span>
          <span slot="renderAccess" slot-scope="text">
            {{ text | accessFilter(type) }}
          </span>
          <span slot="renderAction" slot-scope="text, record">
            <template v-if="type != 'user'">
              <template
                v-if="
                  !~['TabsView', 'PageView', 'RouteView', null].indexOf(
                    record.menuAssembly
                  )
                "
              >
                <!-- <a-dropdown>
									<a class="ant-dropdown-link" @click="e => e.preventDefault()">
										其他权限 <a-icon type="down" />
									</a>
									<a-menu slot="overlay">
										<a-menu-item>
											<a @click="dataAuth(record.id)">数据权限</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="listAuth(record.id)">列表权限</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="formAuth(record.id)">表单权限</a>
										</a-menu-item>
									</a-menu>
								</a-dropdown> -->
                <!-- <a @click="dataAuth(record.id)">数据权限</a> -->
              </template>
            </template>
            <span class="action-margin"></span>
            <template v-if="type != 'user'">
              <a v-if="record.access != 1" @click="handleAccess(record)">{{
                $ct("toGrantAuthorization", "授权")
              }}</a>
              <a
                v-else
                :disabled="roleUuid == '402888e5575f3ab7015760002082076e'"
                :class="
                  roleUuid !== '402888e5575f3ab7015760002082076e'
                    ? 'action-delete'
                    : ''
                "
                @click="handleAccess(record, 'cancellation')"
              >
                {{ $ct("cancelAuth", "取消授权") }}
              </a>
            </template>
            <template v-else>
              <a-popconfirm
                title="确认要取消授权吗?"
                ok-text="确定"
                cancel-text="取消"
                @confirm="removeUser(record)"
              >
                <a class="action-delete">移除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
      </div>
    </a-spin>
    <div
      :style="{
        background: 'rgba(255,255,255,1)',
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            $emit('cancel');
          }
        "
      >
        取消
      </a-button>
    </div>
    <data-auth-list
      ref="dataAuthList"
      :visible="dataAuthListVisible"
      :model="dataAuthListModel"
      @ok="dataAuthListOk"
      @cancel="dataAuthListCancel"
    />
    <list-auth-list
      ref="listAuthList"
      :visible="listAuthListVisible"
      :model="listAuthListModel"
      @ok="listAuthListOk"
      @cancel="listAuthListCancel"
    />
    <form-auth-list
      ref="formAuthList"
      :visible="formAuthListVisible"
      :model="formAuthListModel"
      @ok="formAuthListOk"
      @cancel="formAuthListCancel"
    />
    <personnel-popup
      ref="PersonnelPopup"
      @change="getNewUser"
      :multiple="true"
      :whetherShow="false"
    />
  </t-drawer>
</template>

<script>
import { getFilter } from "@/utils/TopVUI";
import dataAuthList from "./dataAuthList.vue";
import listAuthList from "./listAuthList.vue";
import formAuthList from "./formAuthList.vue";
import { PersonnelPopup } from "@/components";
export default {
  props: {
    visible: {
      type: Boolean,
      default: () => false,
    },
  },
  components: {
    dataAuthList,
    listAuthList,
    formAuthList,
    PersonnelPopup,
  },
  data() {
    return {
      title: "",
      menuCheckedKeys: [],
      menuSelectedKeys: [],
      menuTreeData: [],
      replaceFields: {
        children: "children",
        title: "menuName",
        key: "id",
      },
      loadSuccess: false,
      columns: [
        {
          title: "菜单名称",
          dataIndex: "menuName",
          align: "left",
          ellipsis: true,
        },
        {
          title: "授权状态",
          dataIndex: "access",
          scopedSlots: {
            customRender: "renderAccess",
          },
          customCell: (record, rowIndex) => {
            if (record.access === 1) {
              return {
                style: "color: green",
              };
            } else {
              return {
                style: "color: red",
              };
            }
          },
          ellipsis: true,
        },
        {
          title: "操作",
          dataIndex: "action",
          width: 150,
          align: "center",
          scopedSlots: {
            customRender: "renderAction",
          },
        },
      ],
      selectedRowKeys: [],
      rowData: {},
      pageClientHeight: 0,
      dataLength: 0,
      type: "",
      loading: false,
      loadingText: "",
      pagination: {
        pageNo: 1,
        pageSize: 20,
        showSizeChanger: true,
        showQuickJumper: true,
        hideOnSinglePage: false,
        pageSizeOptions: ["20", "50", "100", "500"],
        showTotal: (total, range) =>
          this.$ct("tablePagingTotal", "共 " + total + " 条", { total: total }),
        onShowSizeChange: (current, pageSize) =>
          this.onShowSizeChange(current, pageSize),
      },
      queryParam: {},
      scrollX: "100%",
      dataAuthListVisible: false,
      listAuthListVisible: false,
      formAuthListVisible: false,
      dataAuthListModel: null,
      listAuthListModel: null,
      formAuthListModel: null,
      roleId: "",
      roleUuid: "",
    };
  },
  filters: {
    accessFilter(val, type) {
      let txt = "";
      if (val === 1 || val === "1") {
        txt = "已授权";
      } else if (val === 0) {
        txt = "未授权";
      } else if (type === "data" && !val) {
        txt = "";
      } else {
        txt = "未授权";
      }
      return txt;
    },
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onSelect: (record, selected, selectedRows) => {
          if (!selected) {
            if (record.children) {
              this.cancleCheckedList(record.children);
            }
          } else {
            if (record.children) {
              this.getCheckedList(record.children);
            }
            this.setName([record]);
          }
        },
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    scrollXY() {
      const tdHeight = this.dataLength * 47;
      let height = this.pageClientHeight;
      return this.dataLength >= 20 || height < tdHeight
        ? {
            y: height,
            x: this.scrollX,
          }
        : {
            x: this.scrollX,
          };
    },
  },
  created() {},
  beforeDestroy() {
    this.destroyResizeEvent();
  },
  methods: {
    getList(data, type) {
      this.loading = true;
      this.type = type;
      this.roleId = data.id;
      this.roleUuid = data.uuid;
      let url = "";
      let listStr = "";
      if (type === "web") {
        url = "/system/authAccess/getListAccessWebMenuByRoleId";
        listStr = "SysButtonList";
      } else if (type === "app") {
        url = "/system/authAccess/getListAccessAppMenuByRoleId";
        listStr = "SysAppMenuList";
      } else if (type === "user") {
        url = "/mdata/user/getPageSetUserByRoleId";
        listStr = "rows";
        this.columns = [
          {
            title: "头像",
            align: "center",
            dataIndex: "userHeadPortrait",
            scopedSlots: {
              customRender: "renderUserHeadPortrait",
            },
            width: 100,
          },
          {
            title: "用户姓名",
            align: "center",
            dataIndex: "userName",
          },
          {
            title: "用户账号",
            align: "center",
            dataIndex: "userNameId",
          },
          {
            title: "所属组织",
            align: "center",
            dataIndex: "orgName",
          },
          {
            title: "操作",
            dataIndex: "action",
            width: 150,
            align: "center",
            scopedSlots: {
              customRender: "renderAction",
            },
          },
        ];
        this.queryParam.pageSize = this.pagination.pageSize;
        this.queryParam.pageNo = this.pagination.pageNo;
        this.queryParam.id = this.roleId;
      } else if (type === "data") {
        url = "/system/sysDataAuth/getListByPid";
        this.queryParam.roleType = "menu";
        this.scrollX = 800;
        this.columns = [
          {
            title: "名称",
            dataIndex: "text",
            width: 300,
          },
          {
            title: "资源地址",
            dataIndex: "href",
            width: 300,
          },
          {
            title: "授权状态",
            dataIndex: "status",
            width: 80,
            scopedSlots: {
              customRender: "renderAccess",
            },
            customCell: (record, rowIndex) => {
              if (record.status == 1) {
                return {
                  style: "color: green",
                };
              } else {
                return {
                  style: "color: red",
                };
              }
            },
          },
          {
            title: "操作",
            dataIndex: "action",
            width: 150,
            align: "center",
            fixed: "right",
            scopedSlots: {
              customRender: "renderAction",
            },
          },
        ];
      }
      this.resizeHandler();
      this.initResizeEvent();
      this.selectedRowKeys = [];
      this.rowData = data;
      this.queryParam.roleId = data.id;
      this.$post(url, this.queryParam)
        .then((res) => {
          let data = res.data;
          if (res.statusCode === 200) {
            if (this.type === "user") {
              const pager = {
                ...this.pagination,
              };
              pager.total = data.totalCount;
              this.pagination = pager;
            }
            if (this.type === "data") {
              let sourceData = [];
              let children = [];
              data.forEach((e) => {
                if (e.pid == 1) {
                  e.key = e.id;
                  e.children = e.state === "closed" ? [] : "";
                  sourceData.push(e);
                } else {
                  children.push(e);
                }
              });
              data = getFilter(sourceData, children);
            }
            this.menuTreeData = listStr ? data[listStr] : data;
            this.menuCheckedKeys = data.menuIds;
            this.menuSelectedKeys = data.menuIds;
            this.dataLength = data.totalCount;
            this.loadSuccess = true;
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    setName(datas) {
      //遍历树  获取id数组
      for (var i in datas) {
        if (datas[i].children) {
          //存在子节点就递归
          this.setName(datas[i].children);
        }
      }
    },
    //勾选被选中的子级数据
    getCheckedList(children) {
      children.forEach((e) => {
        this.selectedRowKeys.push(e.id);
        if (e.children) this.getCheckedList(e.children);
      });
    },
    //取消被选中的子级数据
    cancleCheckedList(list) {
      let keyIndex = -1;
      list.forEach((m) => {
        keyIndex = this.selectedRowKeys.indexOf(m.id);
        this.selectedRowKeys.splice(keyIndex, 1);
        if (m.children) this.cancleCheckedList(m.children);
      });
    },
    handleAccess(e, type) {
      let key = this.selectedRowKeys;
      let url = "";
      if (e === "all") {
        if (this.selectedRowKeys.length === 0) {
          this.$message.warn("请先选择需要操作的数据");
          return;
        }
      } else {
        key = [e.id];
      }
      this.loading = true;
      this.loadingText = "授权中...";
      let params = {
        roleId: this.rowData.id,
        menuId: JSON.stringify(key),
        type: type,
      };
      if (this.type === "web") {
        url = "/system/authAccess/authorize";
      } else if (this.type === "app") {
        url = "/system/authAccess/appAuthorize";
      } else if (this.type === "data") {
        if (type === "cancellation") {
          url = "/system/sysDataAuth/cancelRule";
        } else {
          url = "/system/sysDataAuth/addRule";
        }
        params = {
          roleId: this.rowData.id,
          uuid: key.toString(),
        };
      }
      this.$post(url, params).then((res) => {
        if (res.statusCode === 200) {
          this.getList(this.rowData, this.type);
          this.$message.success(res.message, 1.5);
        } else {
          this.$message.error(res.message, 1.5);
        }
      });
    },
    dataAuth(menuId) {
      this.dataAuthListVisible = true;
      this.$refs.dataAuthList.loadData(menuId, this.queryParam.roleId);
    },
    listAuth(menuId) {
      this.listAuthListVisible = true;
      this.$refs.listAuthList.loadData(menuId, this.queryParam.roleId);
    },
    formAuth(menuId) {
      this.formAuthListVisible = true;
      this.$refs.formAuthList.loadData(menuId, this.queryParam.roleId);
    },
    dataAuthListOk() {
      this.dataAuthListVisible = false;
    },
    listAuthListOk() {
      this.listAuthListVisible = false;
    },
    formAuthListOk() {
      this.formAuthListVisible = false;
    },
    dataAuthListCancel() {
      this.dataAuthListVisible = false;
    },
    listAuthListCancel() {
      this.listAuthListVisible = false;
    },
    formAuthListCancel() {
      this.formAuthListVisible = false;
    },
    addUser() {
      this.$refs.PersonnelPopup.openModal();
    },
    getNewUser(data) {
      this.$post("/mdata/user/cancelOraddUserRole", {
        roleId: this.roleId,
        userNameId: data,
        type: "add",
      }).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success("添加用户成功");
          this.getList(this.rowData, this.type);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    removeUser(record) {
      this.$post("/mdata/user/cancelOraddUserRole", {
        roleId: this.roleId,
        userNameId: record.userNameId,
        type: "cancel",
      }).then((res) => {
        if (res.statusCode === 200) {
          this.$message.success("取消授权成功");
          this.getList(this.rowData, this.type);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    onShowSizeChange(current, pageSize) {
      const pager = { ...this.pagination };
      pager.pageSize = pageSize;
      pager.pageNo = current;
      this.pagination = pager;
      this.getList(this.rowData, this.type);
    },
    pageChange(page, pageSize) {
      const pager = { ...this.pagination };
      pager.pageSize = page.pageSize;
      pager.pageNo = page.current;
      this.pagination = pager;
      this.getList(this.rowData, this.type);
    },
    resizeHandler() {
      this.pageClientHeight = document.getElementsByClassName(
        "table-content"
      )[0]?.clientHeight;
    },
    //监听resize
    initResizeEvent() {
      window.addEventListener("resize", this.resizeHandler, false);
    },
    //移除resize
    destroyResizeEvent() {
      window.removeEventListener("resize", this.resizeHandler);
    },
  },
};
</script>

<style lang="less" scoped>
.business-license {
  cursor: pointer;
  padding: 5px;
  height: 36px !important;
  width: 36px !important;
}
/deep/.ant-drawer-body {
  padding: 0 !important;
}

.toolbar {
  padding: 8px 0 0 5px;
}

/deep/.ant-btn-link {
  border: none !important;
}
/deep/.ant-btn-link:disabled {
  background-color: #fff;
}
/deep/.ant-btn-link:disabled:hover {
  background-color: #fff;
}
.table-content {
  overflow: auto;
  height: calc(100vh - 155px);
}
</style>
